package cn.kbyue.security.security;

import cn.hutool.core.date.DateUnit;
import cn.kbyue.security.constants.CachePrefixEnum;
import cn.kbyue.security.utils.CacheLocalUtil;
import cn.kbyue.security.utils.JwtTokenUtil;
import cn.kbyue.security.utils.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

/**
 * 用户登录成功处理类
 *
 * @author xl
 * @date 2020/4/19 15:13
 */
@Slf4j
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 登录成功的返回
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // 其他处理: 将用户的角色权限等信息放入缓存中提升效率
        DefinedUserDetails userDetails = (DefinedUserDetails) authentication.getPrincipal();
        String accessToken = JwtTokenUtil.createToken(userDetails);

        // 缓存用户信息
        cacheUser(userDetails.getUser().getUserId(), userDetails.getAuthorities());
        log.info("***** 登录成功, userInfo: {}", userDetails);

        Result<Object> success = Result.success("登录成功", accessToken);
        Result.responseResult(response, success);
    }

    private void cacheUser(String userId, Collection<? extends GrantedAuthority> authorities) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String userInfo = mapper.writeValueAsString(authorities);
        CacheLocalUtil.put(CachePrefixEnum.LOGIN_USER + userId, userInfo, DateUnit.HOUR.getMillis() * 2);
    }
}
